import std/algorithm
import std/pegs
import std/sugar
import std/unicode

from std/strutils import join

func isPalindrome*[T](s: seq[T]): bool =
  s == s.reversed

func isPalindrome*(str: string): bool =
  str.toRunes.isPalindrome

func palindromize*(str: string, minimal = true): string =
  if str == "":
    return ""
  let runes = str.toRunes
  if minimal:
    var start = 0
    while not runes[start..^1].isPalindrome:
      inc start
    result = $(runes & runes[0..<start].reversed)
  else:
    result = $(runes & runes[0..^2].reversed)

proc palindromizeWords*(str: string, minimal = true): string =
  str.replace(peg"{\letter+}", (match, count, captures) => captures[0].palindromize(minimal))

when isMainModule:
  import cligen

  proc aibohphobia(minimal = true) =
    stdout.write stdin.readAll.palindromizeWords(minimal)

  dispatch(aibohphobia)
